package com.hyy.nio.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
       /* // 使用 nio 来理解重塞模式，单线程

        //0.ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1.创建了服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        // 2.绑定监听端口
        ssc.bind(new InetSocketAddress(8080));
        //3.连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // 4.accept 建立与客户端连接SocketChannel 用来与客户端之间通1
//            log.debug("connecting...");
            SocketChannel sc = ssc.accept();
            if(sc!=null){
                log.debug("connected...{}", sc);
                channels.add(sc);
                sc.configureBlocking(false);
            }

            for (SocketChannel channel : channels) {
                //5.接收客户端发送的数据
//                log.debug("before read...{}", channel);
                int read = channel.read(buffer);
                if(read>0){
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("after read...{}", channel);
                }

            }
        }*/

        //1、创建selector，管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        //2、建立selector和channel的联系（注册）
        //SelectionKey 事件发生后，通过它可以知道事件和哪个channel的事件
        SelectionKey sscKey = ssc.register(selector, 0, null);
        //只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("register key--{}",sscKey);


        ssc.bind(new InetSocketAddress(8080));

        while (true) {
            //3、调用select 方法，没有事件发生， 线程阻塞，有事件，线程才会恢复运行
            selector.select();
            //4、处理事件selectedKeys内部包含了所有发生的事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){

                SelectionKey key = iterator.next();
                //处理key的时候，要从selectedKeys中删除，否则还会重复处理相同的key
                iterator.remove();
                log.debug("SelectionKey key--{}",key);
                //5、区分事件类型
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    //新建每个socketChannel对应的唯一的一个ByteBuffer
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    SelectionKey scKey = sc.register(selector, 0, buffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}",sc);
                }else if(key.isReadable()){ //读取事件
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);//正常断开返回值是-1
                        if(read==-1){
                            log.debug("channel---{}----close", channel);
                            key.cancel();
                        }else{
//                            buffer.flip();
//                            debugRead(buffer);
//                            buffer.clear();
//                            log.debug("read...{}", channel);
                            split(buffer);
                            if(buffer.position()==buffer.limit()){
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity()*2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                        //客户端断开了，所以将事件取消
                        key.cancel();
                    }

                }

//                key.cancel();
            }

        }


    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            char b = (char) source.get(i);
            if(b=='\n'){
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
//                debugAll(target);
                target.flip();
                String str1 = StandardCharsets.UTF_8.decode(target).toString();
                System.out.println("str1 = " + str1);
            }
        }
        source.compact();
//        debugAll(source);
    }
}